第4章第1节练习题14 满二叉树已知先序序列求解后序序列

问题描述

设有一颗满二叉树(所有节点值均不同),已知其先序序列pre,设计一个算法求其后序序列post

算法思想

对于一般二叉树,仅根据先序或者后序序列并不能确定出另一个遍历序列,但对于满二叉树,任一节点的左、右子树均含有相等的节点数。或者说,按照几何形状来划分呈轴对称,即可以根据先序序列和满二叉树这两个条件便可以将该二叉树画出来。
满二叉树中,先序序列的第一个节点作为后序序列的最后一个节点,由此便可以得出将先序序列 pre[l1h1] 转换为后序序列 post[l2h2] 的递归模型;

f(pre,l1,h1,post,l2,h2)=,f(pre,l1+1,l1+half,post,l2,l2+half1),f(pre,l1+half+1,h1,post,l2+half,h21),h1<l1 half=h1l22h1>l1h1>l1

算法描述

void PreToPost(ElemType* pre, int l1, int h1, ElemType* post, int l2, int h2)
{
    int half;
    if(h1>=l1){
        post[h2]=pre[l1];
        half=(h1-l1)/2;
        PreToPost(pre,l1+1,l1+half,post,l2,l2+half-1);
        PreToPost(pre,l1+half+1,h1,post,l2+half,h2-1);
    }
}

具体代码见附件。


附件

#include<stdio.h>
#include<stdlib.h>
#define MaxSize 100
typedef char ElemType;

void PreToPost(ElemType*,int,int,ElemType*,int,int);

int main(int argc,char* argv[])
{
    ElemType pre[MaxSize]="ABCDEFG";
    ElemType post[MaxSize];

    PreToPost(pre,0,6,post,0,6);

    printf("PreOrder  is %s\n",pre);
    printf("PostOrder is ");
    for(int i=0;i<=6;i++){
        printf("%c",post[i]);
    }
    printf("\n");

    return 0;
}

void PreToPost(ElemType* pre, int l1, int h1, ElemType* post, int l2, int h2)
{
    int half;
    if(h1>=l1){
        post[h2]=pre[l1];
        half=(h1-l1)/2;
        PreToPost(pre,l1+1,l1+half,post,l2,l2+half-1);
        PreToPost(pre,l1+half+1,h1,post,l2+half,h2-1);
    }
}
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
对于满二叉树,可以通过后序序列转换为先序序列的方法如下: 1. 后序序列的最后一个元素是根点。 2. 在后序序列中,根点前面的元素都是根点的子点。 3. 在先序序列中,子点的顺序是先左后右。 4. 所以,在后序序列中找到根点后,可以将后序序列的剩余部分分成两部分,一部分是左子树的后序序列,一部分是右子树的后序序列。 5. 分别对左右子树进行递归处理,即可得到左右子树的先序序列。 6. 将根点加在先序序列的最前面,再加上左子树的先序序列和右子树的先序序列,即为整个二叉树先序序列。 以下是一个示例代码实现(使用Python): ```python def postorder_to_preorder(postorder): if not postorder: return [] root = postorder[-1] # 后序序列的最后一个元素是根点 left_postorder = [] right_postorder = [] # 找到左子树和右子树的后序序列 for num in postorder[:-1]: if num < root: left_postorder.append(num) else: right_postorder.append(num) # 递归处理左右子树,得到先序序列 left_preorder = postorder_to_preorder(left_postorder) right_preorder = postorder_to_preorder(right_postorder) # 返回整个二叉树先序序列 return [root] + left_preorder + right_preorder # 示例调用 postorder = [4, 5, 2, 6, 7, 3, 1] preorder = postorder_to_preorder(postorder) print(preorder) ``` 输出结果为:[1, 2, 4, 5, 3, 6, 7] 希望能够帮助到你!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值